
#include "usart.h"
#include <stdio.h>
#include <string.h>
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"  
#include "freertos/task.h" 
/**
 * @brief       初始化串口
 * @param       baudrate: 波特率, 根据自己需要设置波特率值
 * @note        注意: 必须设置正确的时钟源, 否则串口波特率就会设置异常.
 * @retval      无
 */
void usart_init2(uint32_t baudrate)
{
    uart_config_t uart_config;                          /* 串口配置句柄 */

    uart_config.baud_rate = baudrate;                   /* 波特率 */
    uart_config.data_bits = UART_DATA_8_BITS;           /* 字长为8位数据格式 */
    uart_config.parity = UART_PARITY_DISABLE;           /* 无奇偶校验位 */
    uart_config.stop_bits = UART_STOP_BITS_1;           /* 一个停止位 */
    uart_config.flow_ctrl = UART_HW_FLOWCTRL_DISABLE;   /* 无硬件控制流 */
    uart_config.source_clk = UART_SCLK_DEFAULT;             /* 配置时钟源 *//////
    uart_config.rx_flow_ctrl_thresh = 122;              /* 硬件控制流阈值 */
    uart_param_config(USART_UX, &uart_config);          /* 配置uart端口 */

    /* 配置uart引脚 */
    uart_set_pin(USART_UX, USART_TX_GPIO_PIN, USART_RX_GPIO_PIN, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);

    /* 安装串口驱动 */
    uart_driver_install(USART_UX, RX_BUF_SIZE * 2, RX_BUF_SIZE * 2, 20, NULL, 0);

}
 void rs485_2rts(void)
{
    gpio_config_t gpio_init_struct = {0};

    gpio_init_struct.intr_type = GPIO_INTR_DISABLE;         /* 失能引脚中断 */
    gpio_init_struct.mode = GPIO_MODE_INPUT_OUTPUT;         /* 输入输出模式 */
    gpio_init_struct.pull_up_en = GPIO_PULLUP_ENABLE;       /* 使能上拉 */
    gpio_init_struct.pull_down_en = GPIO_PULLDOWN_DISABLE;  /* 失能下拉 */
    gpio_init_struct.pin_bit_mask = 1ull << RS485_2RTS;   /* 设置的引脚的位掩码 */
    gpio_config(&gpio_init_struct);                         /* 配置GPIO */
}




 void usart_init1(uint32_t baudrate)
{
    uart_config_t uart_config;                          /* 串口配置句柄 */

    uart_config.baud_rate = baudrate;                   /* 波特率 */
    uart_config.data_bits = UART_DATA_8_BITS;           /* 字长为8位数据格式 */
    uart_config.parity = UART_PARITY_DISABLE;           /* 无奇偶校验位 */
    uart_config.stop_bits = UART_STOP_BITS_1;           /* 一个停止位 */
    uart_config.flow_ctrl = UART_HW_FLOWCTRL_DISABLE;   /* 无硬件控制流 */
    uart_config.source_clk = UART_SCLK_DEFAULT;             /* 配置时钟源 *//////
    uart_config.rx_flow_ctrl_thresh = 122;              /* 硬件控制流阈值 */
    uart_param_config(USART0_UX, &uart_config);          /* 配置uart端口 */

    /* 配置uart引脚 */
    uart_set_pin(USART0_UX, USART0_TX_GPIO_PIN, USART0_RX_GPIO_PIN, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);

    /* 安装串口驱动 */
    uart_driver_install(USART0_UX, RX_BUF_SIZE * 2, RX_BUF_SIZE * 2, 20, NULL, 0);

}
 void rs485_1rts(void)
{
    gpio_config_t gpio_init_struct = {0};

    gpio_init_struct.intr_type = GPIO_INTR_DISABLE;         /* 失能引脚中断 */
    gpio_init_struct.mode = GPIO_MODE_INPUT_OUTPUT;         /* 输入输出模式 */
    gpio_init_struct.pull_up_en = GPIO_PULLUP_ENABLE;       /* 使能上拉 */
    gpio_init_struct.pull_down_en = GPIO_PULLDOWN_DISABLE;  /* 失能下拉 */
    gpio_init_struct.pin_bit_mask = 1ull << RS485_1RTS;   /* 设置的引脚的位掩码 */
    gpio_config(&gpio_init_struct);                         /* 配置GPIO */
}

/********************************************************************************************************************/
 /* Uart Events Example
 
	This example code is in the Public Domain (or CC0 licensed, at your option.)
 
	Unless required by applicable law or agreed to in writing, this
	software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
	CONDITIONS OF ANY KIND, either express or implied.
 */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "nvs_flash.h"
#include "driver/uart.h"
#include "freertos/queue.h"
#include "esp_log.h"
 
void echo_send(const int port, const char* str, uint8_t length)
 {
	 if (uart_write_bytes(port, str, length) != length) {
		 // add your code to handle sending failure here
		 abort();
	 }
 }
 
 // An example of echo test with hardware flow control on UART
 void usart_init11(void)
 {
	 const int uart_num = ECHO_UART_PORT;
	 uart_config_t uart_config = {
		 .baud_rate = BAUD_RATE,
		 .data_bits = UART_DATA_8_BITS,
		 .parity = UART_PARITY_DISABLE,
		 .stop_bits = UART_STOP_BITS_1,
		 .flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
		 .rx_flow_ctrl_thresh = 122,
		 .source_clk = UART_SCLK_DEFAULT,
	 };
 
	 ESP_ERROR_CHECK(uart_driver_install(uart_num, BUF_SIZE * 2, 0, 0, NULL, 0));
 
	 // Configure UART parameters
	 ESP_ERROR_CHECK(uart_param_config(uart_num, &uart_config));
 
 
	 // Set UART pins as per KConfig settings
	 ESP_ERROR_CHECK(uart_set_pin(uart_num, ECHO_TEST_TXD, ECHO_TEST_RXD, ECHO_TEST_RTS, ECHO_TEST_CTS));
 
	 // Set RS485 half duplex mode
	 ESP_ERROR_CHECK(uart_set_mode(uart_num, UART_MODE_RS485_HALF_DUPLEX));
 
	 // Set read timeout of UART TOUT feature
	 ESP_ERROR_CHECK(uart_set_rx_timeout(uart_num, ECHO_READ_TOUT));
 
 }
 void usart_init22(void)
 {
	 const int uart_num = UART_PORT_NUM2;
	 uart_config_t uart_config = {
		 .baud_rate = BAUD_RATE,
		 .data_bits = UART_DATA_8_BITS,
		 .parity = UART_PARITY_DISABLE,
		 .stop_bits = UART_STOP_BITS_1,
		 .flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
		 .rx_flow_ctrl_thresh = 122,
		 .source_clk = UART_SCLK_DEFAULT,
	 };
 
	 ESP_ERROR_CHECK(uart_driver_install(uart_num, BUF_SIZE * 2, 0, 0, NULL, 0));
 
	 // Configure UART parameters
	 ESP_ERROR_CHECK(uart_param_config(uart_num, &uart_config));
 
	 // Set UART pins as per KConfig settings
	 ESP_ERROR_CHECK(uart_set_pin(uart_num, UART_TXD2, UART_RXD2, UART_RTS2, ECHO_TEST_CTS));
 
	 // Set RS485 half duplex mode
	 ESP_ERROR_CHECK(uart_set_mode(uart_num, UART_MODE_RS485_HALF_DUPLEX));
 
	 // Set read timeout of UART TOUT feature
	 ESP_ERROR_CHECK(uart_set_rx_timeout(uart_num, ECHO_READ_TOUT));
 
 }
 void RS485_TxRx111(void)
 {
 
   uint8_t len = 0;
   unsigned char data[RX_BUF_SIZE] = {0};

		 uart_get_buffered_data_len(ECHO_UART_PORT, (size_t*) &len); 						 /* 获取环形缓冲区数据长度 */
		 if (len > 0)																	 /* 判断数据长度 */
		 {
			 memset(data, 0, RX_BUF_SIZE);												 /* 对缓冲区清零 */
			 printf("RS485_1\r\n");
			 uart_read_bytes(ECHO_UART_PORT, data, len, 100);								 /* 读数据 */

			 uart_write_bytes(ECHO_UART_PORT, (const char*)data, strlen((const char*)data));  /* 写数据 */
			 esp_err_t ret = uart_wait_tx_done(ECHO_UART_PORT, portMAX_DELAY);
			 if (ret == ESP_OK) {
				 printf("Data sent successfully.\n");
			 } else {
				 printf("Failed to send data.\n");
			 }
	 }
 }
 void RS485_TxRx222(void)
 {
 
   uint8_t len = 0;
   unsigned char data[RX_BUF_SIZE] = {0};
 
		 uart_get_buffered_data_len(UART_PORT_NUM2, (size_t*) &len);						 /* 获取环形缓冲区数据长度 */
		 if (len > 0)																	 /* 判断数据长度 */
		 {
			 memset(data, 0, RX_BUF_SIZE);												 /* 对缓冲区清零 */
			 printf("RS485_2\r\n");
			 uart_read_bytes(UART_PORT_NUM2, data, len, 100);								 /* 读数据 */
 
			 uart_write_bytes(UART_PORT_NUM2, (const char*)data, strlen((const char*)data));  /* 写数据 */
			 esp_err_t ret = uart_wait_tx_done(UART_PORT_NUM2, portMAX_DELAY);
			 if (ret == ESP_OK) {
				 printf("Data sent successfully.\n");
			 } else {
				 printf("Failed to send data.\n");
			 }
	 }
 }

void RS485_TxRx11(void)
 {
	 unsigned char data[BUF_SIZE];
	 //Read data from UART
	 int len = uart_read_bytes(ECHO_UART_PORT, data, BUF_SIZE, PACKET_READ_TICS);

	 //Write data back to UART
	 if (len > 0) {
		 //echo_send(uart_num, "\r\n", 2);
		 printf("\r\n");
		 printf("	RS485_1		");
		 printf("[ ");
		 for (int i = 0; i < len; i++) {
			 printf("0x%.2X ", (uint8_t)data[i]);
			 echo_send(ECHO_UART_PORT, (const char*)&data[i], 1);
			 // Add a Newline character if you get a return charater from paste (Paste tests multibyte receipt/buffer)
			 if (data[i] == '\r') {
				 echo_send(ECHO_UART_PORT, "\n", 1);
			 }
		 }
		 printf("] \n");
		 //echo_send(uart_num, "]\r\n", 3);
	 } else {
		 char data1[5] = {0x11,0x11,0x11};
		 echo_send(ECHO_UART_PORT,data1, strlen(data1));
		 ESP_ERROR_CHECK(uart_wait_tx_done(ECHO_UART_PORT, 10));
		 vTaskDelay(500);
	 }
 
}


void RS485_TxRx22(void)
 {
	 char data[BUF_SIZE];
	 //Read data from UART
	 int len = uart_read_bytes(UART_PORT_NUM2, data, BUF_SIZE, PACKET_READ_TICS);

	 //Write data back to UART
	 if (len > 0) {
		 //echo_send(uart_num, "\r\n", 2);
		 printf("\r\n");
		 printf("	RS485_2		");
		 printf("[ ");
		 for (int i = 0; i < len; i++) {
			 printf("0x%.2X ", (uint8_t)data[i]);
			 echo_send(UART_PORT_NUM2, (const char*)&data[i], 1);
			 // Add a Newline character if you get a return charater from paste (Paste tests multibyte receipt/buffer)
			 if (data[i] == '\r') {
				 echo_send(UART_PORT_NUM2, "\n", 1);
			 }
		 }
		 printf("] \n");
		 //echo_send(uart_num, "]\r\n", 3);
	 } else {
		 // Echo a "." to show we are alive while we wait for input
		 char data1[5] = {0x22,0x22,0x22};
		 echo_send(UART_PORT_NUM2,data1, strlen(data1));
		 ESP_ERROR_CHECK(uart_wait_tx_done(UART_PORT_NUM2, 10));
		 vTaskDelay(500);
	 }
 
}

